var CurrentUser;    // Global variable

function getName() {
    try {
        var user = JSON.parse(localStorage.getItem("loggedinUser"));
        CurrentUser = user;
        if (user) {
            console.log("Currently logged in:  " + user["name"]);
            const nameElement = document.getElementById("name-goes-here");
            if (nameElement) nameElement.innerText = user["name"];
        } else {
            console.log("No one is logged in");
        }
    } catch (error) {
        console.error("Error parsing user data:", error);
    }
}

getName(); // Run the function

function populateHistory() {
    // 检查 CurrentUser 是否存在
    if (!CurrentUser || !CurrentUser.email) {
        console.log("No user logged in or invalid user data");
        return;
    }

    try {
        var users = JSON.parse(localStorage.getItem("users")) || [];
        const user = users.find(u => u.email === CurrentUser.email);

        if (user && user.history && user.history.length > 0) {
            const historyArray = user.history;
            const historyCardTemplate = document.getElementById("postCardTemplate");
            const historyCardGroup = document.getElementById("history-goes-here");

            if (!historyCardTemplate || !historyCardGroup) {
                console.log("Template or container elements not found");
                return;
            }

            historyArray.forEach((hist, index) => {
                let onecard = historyCardTemplate.content.cloneNode(true);

                onecard.querySelector(".date").textContent = hist.date;
                onecard.querySelector(".count").textContent = hist.calories;
                onecard.querySelector(".card-description").textContent = hist.details;
                // 修复路径中的空格
                onecard.querySelector('.card-image').src = "./images/" + hist.imageName;
                
                // 使用箭头函数创建闭包，捕获当前 index
                onecard.querySelector('.editButton').onclick = () => editHistory(index);
                
                const deleteButton = onecard.querySelector('.deleteButton');
                if (deleteButton) {
                    deleteButton.onclick = () => deleteHistory(index);
                }
                
                historyCardGroup.appendChild(onecard);
            });
        } else {
            console.log("No history data found for user");
        }
    } catch (error) {
        console.error("Error populating history:", error);
    }
}

populateHistory();

function deleteHistory(id) {
    if (!CurrentUser || !CurrentUser.email) {
        console.log("No user logged in");
        return;
    }

    try {
        var users = JSON.parse(localStorage.getItem("users")) || [];
        const user = users.find(u => u.email === CurrentUser.email);

        if (user && user.history && id < user.history.length) {
            if (confirm("Are you sure you want to delete: " +
                user.history[id].details + " added on " +
                user.history[id].date)) {

                user.history.splice(id, 1);
                localStorage.setItem("users", JSON.stringify(users));
                alert("History Deleted.");
                location.reload();
            }
        } else {
            console.log("Invalid history index or user data");
        }
    } catch (error) {
        console.error("Error deleting history:", error);
    }
}

function editHistory(id) {
    if (!CurrentUser || !CurrentUser.email) {
        console.log("No user logged in");
        return;
    }
    
    try {
        var parameters = new URLSearchParams();
        parameters.append("id", id);
        location.href = "../post.html?" + parameters.toString();
    } catch (error) {
        console.error("Error navigating to edit page:", error);
    }
}